package com.its.cloud.controller;

import com.its.cloud.entity.Payment;
import com.its.cloud.entity.ResultBean;
import com.its.cloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author huguangjun
 * @className PaymentController
 * @date 2021/1/11
 * @desc 17:24
 */
@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    // 服务注册发现
    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping(value = "/payment/create")
    public ResultBean create(@RequestBody Payment payment) {
        try {
            TimeUnit.SECONDS.sleep(5);
            paymentService.create(payment);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("创建错误：", e);
        }
        return new ResultBean(payment.getId() + ",server-port:" + serverPort);
    }

    @GetMapping(value = "/payment/get/{id}")
    public ResultBean get(@PathVariable("id") Long id) {
        try {
            // test gateway http's timeout is ok
            //TimeUnit.SECONDS.sleep(12);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Payment payment = null;
        try {
            payment = paymentService.getPaymentById(id);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询错误：", e);
        }
        return new ResultBean(payment + ",server-port:" + serverPort);
    }

    @GetMapping(value = "/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            log.info("###element:"+element);
        }
        // 根据服务名称查找
        List<ServiceInstance> instances = discoveryClient.getInstances("PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info("###instance:"+instance.getServiceId() + "\t" +
                    instance.getHost() + "\t" +
                    instance.getPort() + "\t" +
                    instance.getUri() + "\t");
        }
        return this.discoveryClient;
    }
}
